package com.ic.loan.activity

import android.os.Bundle
import android.widget.ImageView
import com.gyf.immersionbar.ktx.immersionBar
import com.ic.loan.R
import kotlinx.android.synthetic.main.activity_my_infomation.*

import com.bigkoo.pickerview.builder.OptionsPickerBuilder

import com.bigkoo.pickerview.view.OptionsPickerView
import com.blankj.utilcode.util.*
import com.bumptech.glide.Glide
import com.ic.loan.bean.ImageBean
import com.ic.loan.http.ApiUrl
import com.ic.loan.http.HttpUtils
import com.ic.loan.http.ResultListener
import com.ic.loan.pop.SelectPicturePop
import com.ic.loan.utils.GlideEngine
import com.luck.picture.lib.entity.LocalMedia

import com.luck.picture.lib.listener.OnResultCallbackListener

import com.luck.picture.lib.config.PictureMimeType

import com.luck.picture.lib.PictureSelector
import com.lxj.xpopup.XPopup
import java.io.File


class MyInformationActivity : BaseActivity() {
    private var frontUrl: String? = null
    private var backUrl: String? = null
    private var cardFrontUrl: String? = null
    private val optList: List<String> =
        mutableListOf("10th", "12th", "Graduate", "Post Graduate", "PhD", "Other")
    val sexList: List<String> =
        mutableListOf("Male", "Female")

    override fun onCreate(savedInstanceState: Bundle?) {
        immersionBar {
            statusBarDarkFont(true)
        }
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_infomation)
        initAction()
        tvContinue.setOnClickListener {
            saveUserInfo()
        }
    }

    private fun saveUserInfo() {
        val optStr = tvOpt.text.toString()
        val fullNameStr = edtFullName.text.toString()
        val ageStr = edtAge.text.toString()
        val emailStr = edtEmail.text.toString()
        val aadhaarNumberStr = edtAadhaarNumber.text.toString()
        val panCardNumberStr = edtPanCardNumber.text.toString()
        val sexStr = tvSex.text.toString()
        val accountHolderName = edtAccountHolderName.text.toString()
        val bankAccountNumber = edtBankAccountNumber.text.toString()
        val ifscCodeStr = edtIfscCode.text.toString()
        if (optStr.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_input_opt))
            return
        }
        if (fullNameStr.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_input_full_name))
            return
        }
        if (ageStr.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_input_age))
            return
        }
        if (emailStr.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_input_email))
            return
        }
        if (aadhaarNumberStr.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_input_aadhaar_number))
            return
        }
        if (panCardNumberStr.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_input_pan_card_number))
            return
        }
        if (sexStr.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_input_pan_card_gender))
            return
        }
        if (accountHolderName.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_input_account_holder_name))
            return
        }
        if (bankAccountNumber.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_input_bank_account_number))
            return
        }
        if (ifscCodeStr.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_input_ifsc_code))
            return
        }
        if (frontUrl.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_push_front))
            return
        }
        if (backUrl.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_push_back))
            return
        }
        if (cardFrontUrl.isNullOrBlank()){
            ToastUtils.showShort(getString(R.string.please_pan_card_front))
            return
        }
        showLoading()
        HttpUtils.postOkGo(mutableMapOf(
            "education" to optStr,
            "fullname" to fullNameStr,
            "age" to ageStr,
            "email" to emailStr,
            "gender" to if (sexStr == "Male") {
                1
            } else if (sexStr == "Female") {
                2
            } else {
                0
            },
            "front" to frontUrl!!,
            "back" to backUrl!!,
            "aadhear" to aadhaarNumberStr,
            "pan_card_front" to cardFrontUrl!!,
            "pan_card_number" to panCardNumberStr!!,
            "name" to accountHolderName!!,
            "bank_number" to bankAccountNumber!!,
            "ifsc_code" to ifscCodeStr!!,
        ), ApiUrl.POST_MPROFILE, object : ResultListener() {
            override fun onSucceeded(json: String?) {
                ActivityUtils.startActivity(WhyChooseUsActivity::class.java)
                onBackPressed()
            }

            override fun onLoadFinish() {
                super.onLoadFinish()
                hintLoading()
            }
        })
    }

    private fun initAction() {
        lLItem1.setOnClickListener {
            selectString(optList) {
                tvOpt.text = it
            }
        }
        llSex.setOnClickListener {
            selectString(sexList) {
                tvSex.text = it
            }
        }
        ivBack.setOnClickListener { view ->
            selectPicture {
                Glide.with(this).load(it?.realPath).into(view as ImageView)
                updateImage(File(it?.realPath), 1)
            }
        }
        ivFront.setOnClickListener { view ->
            selectPicture {
                Glide.with(this).load(it?.realPath).into(view as ImageView)
                updateImage(File(it?.realPath), 0)
            }
        }
        ivCardBack.setOnClickListener { view ->
            selectPicture {
                Glide.with(this).load(it?.realPath).into(view as ImageView)
                updateImage(File(it?.realPath), 2)
            }
        }
    }

    private fun updateImage(file: File, index: Int) {
        showLoading()
        HttpUtils.postOkGoForUpdataFile(
            mutableMapOf("timestamp" to System.currentTimeMillis() / 1000),
            "Filedata",
            file,
            ApiUrl.POST_UPLOAD_IMG,
            object : ResultListener() {
                override fun onSucceeded(json: String?) {
                    val imageBean = GsonUtils.fromJson(json, ImageBean::class.java)
                    when (index) {
                        0 -> {
                            frontUrl = imageBean.path
                        }
                        1 -> {
                            backUrl = imageBean.path
                        }
                        2 -> {
                            cardFrontUrl = imageBean.path
                        }
                    }
                }

                override fun onFailed(content: String?) {
                    super.onFailed(content)
                    when(index){
                        0 -> {
                            Glide.with(this@MyInformationActivity).load(R.mipmap.ic_card_front).into(ivFront)                        }
                        1 -> {
                            Glide.with(this@MyInformationActivity).load(R.mipmap.ic_card_back).into(ivCardBack)                                    }
                        2 -> {
                            Glide.with(this@MyInformationActivity).load(R.mipmap.ic_card_front).into(ivCardBack)                                    }
                    }
                }

                override fun onLoadFinish() {
                    hintLoading()
                }

            })
    }

    private fun selectPicture(selectCallback: (LocalMedia?) -> Unit) {
        XPopup.Builder(this).asCustom(SelectPicturePop(this,{
            PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())
                .isOriginalImageControl(true)
                .forResult(object : OnResultCallbackListener<LocalMedia?> {
                    override fun onResult(result: List<LocalMedia?>) {
                        // 结果回调
                        selectCallback.invoke(result[0])
                    }

                    override fun onCancel() {
                        // 取消
                    }
                })
        },{
            PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())
                .isOriginalImageControl(true)
                .forResult(object : OnResultCallbackListener<LocalMedia?> {
                    override fun onResult(result: List<LocalMedia?>) {
                        // 结果回调
                        selectCallback.invoke(result[0])
                    }

                    override fun onCancel() {
                        // 取消
                    }
                })
        })).show()
    }

    private fun selectString(data: List<String>, selectCallback: (String) -> Unit) {
        KeyboardUtils.hideSoftInput(this)
        //条件选择器
        val pvOptions: OptionsPickerView<String> = OptionsPickerBuilder(
            this
        ) { options1, _, _, _ -> //返回的分别是三个级别的选中位置
            selectCallback.invoke(data[options1])
        }
            .setCancelText("Cancel")
            .setCancelColor(ColorUtils.getColor(android.R.color.darker_gray))
            .setSubmitText("Confirm")
            .setSubmitColor(ColorUtils.getColor(android.R.color.holo_blue_dark))
            .setItemVisibleCount(4)
            .setContentTextSize(18)
            .setLineSpacingMultiplier(2.5f)
            .setTitleBgColor(ColorUtils.getColor(android.R.color.white))
            .build()
        pvOptions.setPicker(data)
        pvOptions.show()
    }
}